package com.example.myapplication5.views.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.TextView;

@SuppressLint("AppCompatCustomView")
public class DraggableZoomTextView extends TextView {
    // 矩阵用于处理缩放
    private Matrix matrix = new Matrix();
    private Matrix savedMatrix = new Matrix();
    private float[] matrixValues = new float[9];

    // 手势模式
    private static final int NONE = 0;
    private static final int DRAG = 1;
    private static final int ZOOM = 2;
    private int mode = NONE;

    // 触摸点记录
    private PointF start = new PointF();
    private PointF mid = new PointF();
    private float oldDist = 1f;
    private float startX, startY;

    // 缩放配置
    private float minScale = 0.5f;    // 最小缩放比例
    private float maxScale = 3.0f;    // 最大缩放比例
    private float currentScale = 1.0f; // 当前缩放比例
    private float originalTextSize;   // 初始字体大小（px）

    // 布局参数，用于真正移动View
    private ViewGroup.MarginLayoutParams layoutParams;

    public DraggableZoomTextView(Context context) {
        super(context);
        init();
    }

    public DraggableZoomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public DraggableZoomTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        originalTextSize = getTextSize();
        setClickable(true);
        matrix.reset();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        // 获取布局参数，用于修改位置
        if (getParent() instanceof ViewGroup) {
            layoutParams = (ViewGroup.MarginLayoutParams) getLayoutParams();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 获取父容器，用于请求不拦截触摸事件
        ViewParent parent = getParent();
        if (parent != null) {
            parent.requestDisallowInterceptTouchEvent(true);
        }

        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                // 单指按下，记录初始位置
                savedMatrix.set(matrix);
                start.set(event.getX(), event.getY());
                startX = event.getRawX();
                startY = event.getRawY();
                mode = DRAG;
                break;

            case MotionEvent.ACTION_POINTER_DOWN:
                // 双指按下，准备缩放
                oldDist = spacing(event);
                if (oldDist > 10f) {
                    savedMatrix.set(matrix);
                    midPoint(mid, event);
                    mode = ZOOM;
                }
                break;

            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                // 手势结束
                mode = NONE;
                break;

            case MotionEvent.ACTION_MOVE:
                if (mode == DRAG) {
                    // 拖动整个View - 通过改变布局参数实现
                    if (layoutParams != null) {
                        float dx = event.getRawX() - startX;
                        float dy = event.getRawY() - startY;

                        // 更新位置
                        layoutParams.leftMargin += dx;
                        layoutParams.topMargin += dy;

                        // 应用新布局
                        setLayoutParams(layoutParams);

                        // 更新起始点
                        startX = event.getRawX();
                        startY = event.getRawY();
                    }
                } else if (mode == ZOOM) {
                    // 缩放操作
                    float newDist = spacing(event);
                    if (newDist > 10f) {
                        float scale = newDist / oldDist;
                        applyScale(scale);
                    }
                }
                break;
        }

        invalidate();
        return true;
    }

    /**
     * 应用缩放，同时调整View大小和字体大小
     */
    private void applyScale(float scaleFactor) {
        // 计算新的缩放比例
        float newScale = currentScale * scaleFactor/2.5F;

        // 限制缩放范围
        if (newScale < minScale) newScale = minScale;
        if (newScale > maxScale) newScale = maxScale;

        // 计算实际需要应用的缩放比例
        float actualScale = newScale / currentScale;

        // 应用缩放变换
        matrix.set(savedMatrix);
        matrix.postScale(actualScale, actualScale, mid.x, mid.y);

        // 更新字体大小（与缩放比例同步）
        setTextSize(0, originalTextSize * newScale);

        // 更新当前缩放比例
        currentScale = newScale;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // 保存画布状态
        canvas.save();
        // 应用矩阵缩放变换
        canvas.concat(matrix);
        // 绘制文本
        super.onDraw(canvas);
        // 恢复画布状态
        canvas.restore();
    }

    /**
     * 计算两点之间的距离
     */
    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return (float) Math.sqrt(x * x + y * y);
    }

    /**
     * 计算两点的中点
     */
    private void midPoint(PointF point, MotionEvent event) {
        float x = event.getX(0) + event.getX(1);
        float y = event.getY(0) + event.getY(1);
        point.set(x / 2, y / 2);
    }

    /**
     * 重置到初始状态
     */
    public void reset() {
        matrix.reset();
        currentScale = 1.0f;
        setTextSize(0, originalTextSize);

        // 重置位置
        if (layoutParams != null) {
            layoutParams.leftMargin = 0;
            layoutParams.topMargin = 0;
            setLayoutParams(layoutParams);
        }

        invalidate();
    }

    // 设置和获取方法
    public void setMinScale(float minScale) {
        this.minScale = minScale;
    }

    public void setMaxScale(float maxScale) {
        this.maxScale = maxScale;
    }

    public float getCurrentScale() {
        return currentScale;
    }
}